<template>
  <div class="stagnant-warning-container">
    <el-card class="stagnant-card">
      <template #header>
        <div class="card-header">
          <h3>呆滞料预警</h3>
          <div>
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button type="success" @click="exportData">导出数据</el-button>
            <el-button type="warning" @click="batchHandle" :disabled="!selectedStagnant.length">批量处理</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和过滤区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="物料编码">
            <el-input v-model="filterForm.materialCode" placeholder="请输入物料编码" clearable />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="filterForm.warehouseId" placeholder="请选择仓库" clearable>
              <el-option 
                v-for="warehouse in warehouses" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="呆滞等级">
            <el-select v-model="filterForm.stagnantLevel" placeholder="请选择等级" clearable>
              <el-option label="轻度呆滞" value="light" />
              <el-option label="中度呆滞" value="medium" />
              <el-option label="重度呆滞" value="severe" />
              <el-option label="僵尸物料" value="zombie" />
            </el-select>
          </el-form-item>
          <el-form-item label="无动态天数">
            <el-input-number v-model="filterForm.stagnantDays" :min="0" placeholder="最小天数" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchStagnant">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 统计指标卡片 -->
      <el-row :gutter="20" class="stat-row">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ stats.totalCount }}</div>
            <div class="stat-label">呆滞物料总数</div>
            <div class="stat-trend">
              较上月 <span :class="stats.countTrend > 0 ? 'trend-up' : 'trend-down'">{{ stats.countTrend > 0 ? '+' : '' }}{{ stats.countTrend }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">¥{{ formatCurrency(stats.totalValue) }}</div>
            <div class="stat-label">呆滞物料总价值</div>
            <div class="stat-trend">
              较上月 <span :class="stats.valueTrend > 0 ? 'trend-up' : 'trend-down'">{{ stats.valueTrend > 0 ? '+' : '' }}{{ stats.valueTrend }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ stats.zombieCount }}</div>
            <div class="stat-label">僵尸物料数</div>
            <div class="stat-trend">
              较上月 <span :class="stats.zombieTrend > 0 ? 'trend-up' : 'trend-down'">{{ stats.zombieTrend > 0 ? '+' : '' }}{{ stats.zombieTrend }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ stats.handledRate }}%</div>
            <div class="stat-label">处理完成率</div>
            <div class="stat-trend">
              较上月 <span :class="stats.handledTrend > 0 ? 'trend-down' : 'trend-up'">{{ stats.handledTrend > 0 ? '+' : '' }}{{ stats.handledTrend }}%</span>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 呆滞物料列表 -->
      <el-table
        :data="stagnantList"
        border
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="物料编码" width="120" sortable />
        <el-table-column prop="materialName" label="物料名称" width="150" />
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        <el-table-column prop="locationCode" label="货位" width="100" />
        <el-table-column prop="quantity" label="数量" width="80" sortable />
        <el-table-column prop="unit" label="单位" width="60" />
        <el-table-column prop="unitValue" label="单位价值" sortable>
          <template #default="scope">
            ¥{{ formatCurrency(scope.row.unitValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalValue" label="总价值" width="100" sortable>
          <template #default="scope">
            ¥{{ formatCurrency(scope.row.quantity * scope.row.unitValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastMovementDate" label="最后动态日期" width="140" sortable />
        <el-table-column prop="stagnantDays" label="呆滞天数" width="120" sortable>
          <template #default="scope">
            <span :class="getStagnantDaysClass(scope.row.stagnantDays)">{{ scope.row.stagnantDays }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stagnantLevel" label="呆滞等级" width="100">
          <template #default="scope">
            <el-tag :type="getStagnantLevelType(scope.row.stagnantLevel)">
              {{ getStagnantLevelLabel(scope.row.stagnantLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'pending' ? 'danger' : 'success'">
              {{ scope.row.status === 'pending' ? '待处理' : '已处理' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="210"> 
          <template #default="scope">
            <el-button link type="primary" @click="handleStagnant(scope.row)" v-if="scope.row.status === 'pending'">处理</el-button>
            <el-button link type="primary" @click="viewHistory(scope.row)">动态历史</el-button>
            <el-button link type="primary" @click="analyzeStagnant(scope.row)">分析原因</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 呆滞物料处理对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      :title="batchMode ? '批量处理呆滞物料' : '处理呆滞物料'"
      width="50%"
    >
      <div class="handle-form">
        <div v-if="batchMode" class="batch-summary">
          <p>您选择了 <strong>{{ selectedStagnant.length }}</strong> 个呆滞物料进行处理</p>
          <p>总价值: <strong>¥{{ formatCurrency(calculateTotalValue()) }}</strong></p>
        </div>
        <div v-else class="single-material">
          <p>物料编码: <strong>{{ currentStagnant?.materialCode }}</strong></p>
          <p>物料名称: <strong>{{ currentStagnant?.materialName }}</strong></p>
          <p>呆滞天数: <strong>{{ currentStagnant?.stagnantDays }}</strong> 天</p>
          <p>总价值: <strong>¥{{ formatCurrency(currentStagnant?.quantity * currentStagnant?.unitValue) }}</strong></p>
        </div>
        
        <el-divider content-position="left">处理方式</el-divider>
        
        <el-form :model="handleForm" label-width="100px">
          <el-form-item label="处理类型" prop="handleType">
            <el-select v-model="handleForm.handleType" placeholder="请选择处理类型">
              <el-option label="特价销售" value="discount_sale" />
              <el-option label="内部调拨" value="internal_transfer" />
              <el-option label="退回供应商" value="return_to_supplier" />
              <el-option label="转为备品备件" value="convert_to_spare" />
              <el-option label="报废处理" value="scrap" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="处理原因" prop="reason">
            <el-input type="textarea" v-model="handleForm.reason" rows="3" placeholder="请输入处理原因" />
          </el-form-item>
          
          <el-form-item label="计划完成日期" prop="planDate">
            <el-date-picker v-model="handleForm.planDate" type="date" placeholder="请选择计划完成日期" />
          </el-form-item>
          
          <el-form-item label="负责人" prop="responsible">
            <el-input v-model="handleForm.responsible" placeholder="请输入负责人" />
          </el-form-item>
          
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="handleForm.remarks" rows="2" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">提交</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 动态历史对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="物料动态历史"
      width="60%"
    >
      <div v-if="currentStagnant" class="history-container">
        <el-timeline>
          <el-timeline-item
            v-for="(history, index) in materialHistory"
            :key="index"
            :timestamp="history.date"
            :type="getTimelineItemType(history.type)"
          >
            <h4>{{ history.title }}</h4>
            <p>{{ history.description }}</p>
            <p v-if="history.quantity" class="history-quantity">
              数量: {{ history.quantity > 0 ? '+' + history.quantity : history.quantity }} {{ history.unit }}
            </p>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'StagnantWarning',
  setup() {
    // 状态变量
    const loading = ref(false)
    const handleDialogVisible = ref(false)
    const historyDialogVisible = ref(false)
    const batchMode = ref(false)
    const currentStagnant = ref(null)
    const selectedStagnant = ref([])
    
    // 仓库数据
    const warehouses = ref([
      { id: 'WH001', name: '中央仓库' },
      { id: 'WH002', name: '北区配送中心' },
      { id: 'WH003', name: '南方仓储中心' },
      { id: 'WH004', name: '西部物流中心' }
    ])
    
    // 过滤表单
    const filterForm = reactive({
      materialCode: '',
      warehouseId: '',
      stagnantLevel: '',
      stagnantDays: 60
    })
    
    // 处理表单
    const handleForm = reactive({
      handleType: '',
      reason: '',
      planDate: '',
      responsible: '',
      remarks: ''
    })
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 统计数据
    const stats = reactive({
      totalCount: 58,
      totalValue: 453600,
      zombieCount: 12,
      handledRate: 25,
      countTrend: 5,
      valueTrend: 8,
      zombieTrend: 2,
      handledTrend: 10
    })
    
    // 呆滞物料列表
    const stagnantList = ref([])
    
    // 物料历史
    const materialHistory = ref([])
    
    // 加载呆滞物料数据
    const loadStagnantData = () => {
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        // 生成模拟呆滞物料数据
        stagnantList.value = [
          {
            id: 'S001',
            materialCode: 'RAW10025',
            materialName: '氧化铝陶瓷基板',
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            locationCode: 'A-02-03-04',
            quantity: 500,
            unit: '片',
            unitValue: 45,
            lastMovementDate: '2023-01-15',
            stagnantDays: 550,
            stagnantLevel: 'zombie',
            status: 'pending'
          },
          {
            id: 'S002',
            materialCode: 'PKG20056',
            materialName: '高档礼盒包装',
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            locationCode: 'B-03-02-01',
            quantity: 200,
            unit: '个',
            unitValue: 35,
            lastMovementDate: '2023-10-22',
            stagnantDays: 270,
            stagnantLevel: 'severe',
            status: 'pending'
          },
          {
            id: 'S003',
            materialCode: 'SEMI30089',
            materialName: '液晶显示模块',
            warehouseId: 'WH002',
            warehouseName: '北区配送中心',
            locationCode: 'C-01-04-02',
            quantity: 150,
            unit: '个',
            unitValue: 220,
            lastMovementDate: '2023-12-05',
            stagnantDays: 225,
            stagnantLevel: 'medium',
            status: 'pending'
          },
          {
            id: 'S004',
            materialCode: 'RAW40012',
            materialName: '钛合金板材',
            warehouseId: 'WH003',
            warehouseName: '南方仓储中心',
            locationCode: 'A-04-01-03',
            quantity: 80,
            unit: 'kg',
            unitValue: 350,
            lastMovementDate: '2024-02-18',
            stagnantDays: 150,
            stagnantLevel: 'light',
            status: 'pending'
          },
          {
            id: 'S005',
            materialCode: 'FIN50078',
            materialName: '旧型号传感器',
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            locationCode: 'D-02-02-05',
            quantity: 30,
            unit: '个',
            unitValue: 480,
            lastMovementDate: '2023-05-10',
            stagnantDays: 430,
            stagnantLevel: 'severe',
            status: 'handled'
          }
        ]
        
        // 更新总数
        pagination.total = 58
        
        loading.value = false
      }, 500)
    }
    
    // 搜索呆滞物料
    const searchStagnant = () => {
      pagination.currentPage = 1
      loadStagnantData()
    }
    
    // 重置筛选条件
    const resetFilter = () => {
      Object.assign(filterForm, {
        materialCode: '',
        warehouseId: '',
        stagnantLevel: '',
        stagnantDays: 60
      })
      searchStagnant()
    }
    
    // 刷新数据
    const refreshData = () => {
      loadStagnantData()
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage.success('呆滞物料数据已导出')
    }
    
    // 处理呆滞物料
    const handleStagnant = (item) => {
      currentStagnant.value = item
      batchMode.value = false
      resetHandleForm()
      handleDialogVisible.value = true
    }
    
    // 批量处理
    const batchHandle = () => {
      if (selectedStagnant.value.length === 0) {
        ElMessage.warning('请选择要处理的呆滞物料')
        return
      }
      
      batchMode.value = true
      resetHandleForm()
      handleDialogVisible.value = true
    }
    
    // 重置处理表单
    const resetHandleForm = () => {
      Object.assign(handleForm, {
        handleType: '',
        reason: '',
        planDate: '',
        responsible: '',
        remarks: ''
      })
    }
    
    // 提交处理
    const submitHandle = () => {
      if (!handleForm.handleType) {
        ElMessage.warning('请选择处理类型')
        return
      }
      
      // 模拟API调用
      setTimeout(() => {
        if (batchMode.value) {
          ElMessage.success(`已提交${selectedStagnant.value.length}个呆滞物料的处理方案`)
        } else {
          ElMessage.success(`已提交物料"${currentStagnant.value.materialName}"的处理方案`)
        }
        handleDialogVisible.value = false
        loadStagnantData()
      }, 500)
    }
    
    // 查看动态历史
    const viewHistory = (item) => {
      currentStagnant.value = item
      historyDialogVisible.value = true
      
      // 模拟加载物料历史数据
      setTimeout(() => {
        materialHistory.value = [
          {
            date: '2023-01-15',
            title: '最后入库',
            description: '从供应商"江苏科技材料有限公司"入库',
            type: 'in',
            quantity: 500,
            unit: '片'
          },
          {
            date: '2022-12-10',
            title: '库存盘点',
            description: '年度盘点确认数量',
            type: 'check',
            quantity: null,
            unit: null
          },
          {
            date: '2022-11-05',
            title: '出库',
            description: '生产领用',
            type: 'out',
            quantity: -200,
            unit: '片'
          },
          {
            date: '2022-08-20',
            title: '入库',
            description: '从供应商"江苏科技材料有限公司"入库',
            type: 'in',
            quantity: 700,
            unit: '片'
          }
        ]
      }, 500)
    }
    
    // 分析呆滞原因
    const analyzeStagnant = (item) => {
      ElMessageBox.alert(
        '根据系统分析，该物料呆滞的主要原因是：<br/><br/>' +
        '1. 产品设计变更，导致原材料规格不再适用<br/>' +
        '2. 供应商最小起订量较大，造成超额采购<br/>' +
        '3. 市场需求变化，相关产品销量下滑<br/><br/>' +
        '建议处理方式：特价销售或退回供应商',
        '呆滞原因分析',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定'
        }
      )
    }
    
    // 格式化货币
    const formatCurrency = (value) => {
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
    
    // 计算总价值
    const calculateTotalValue = () => {
      return selectedStagnant.value.reduce((total, item) => {
        return total + (item.quantity * item.unitValue)
      }, 0)
    }
    
    // 获取呆滞等级类型
    const getStagnantLevelType = (level) => {
      switch (level) {
        case 'light':
          return 'info'
        case 'medium':
          return 'warning'
        case 'severe':
          return 'danger'
        case 'zombie':
          return ''
        default:
          return 'info'
      }
    }
    
    // 获取呆滞等级标签
    const getStagnantLevelLabel = (level) => {
      switch (level) {
        case 'light':
          return '轻度呆滞'
        case 'medium':
          return '中度呆滞'
        case 'severe':
          return '重度呆滞'
        case 'zombie':
          return '僵尸物料'
        default:
          return '未知'
      }
    }
    
    // 获取呆滞天数类名
    const getStagnantDaysClass = (days) => {
      if (days >= 365) return 'days-zombie'
      if (days >= 180) return 'days-severe'
      if (days >= 90) return 'days-medium'
      return 'days-light'
    }
    
    // 获取时间线项目类型
    const getTimelineItemType = (type) => {
      switch (type) {
        case 'in':
          return 'primary'
        case 'out':
          return 'success'
        case 'check':
          return 'info'
        default:
          return 'info'
      }
    }
    
    // 选择变更处理
    const handleSelectionChange = (selection) => {
      selectedStagnant.value = selection
    }
    
    // 处理页码变更
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadStagnantData()
    }
    
    // 处理每页条数变更
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadStagnantData()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      loadStagnantData()
    })
    
    return {
      loading,
      warehouses,
      filterForm,
      stagnantList,
      pagination,
      stats,
      handleDialogVisible,
      historyDialogVisible,
      batchMode,
      currentStagnant,
      selectedStagnant,
      handleForm,
      materialHistory,
      
      searchStagnant,
      resetFilter,
      refreshData,
      exportData,
      handleStagnant,
      batchHandle,
      submitHandle,
      viewHistory,
      analyzeStagnant,
      formatCurrency,
      calculateTotalValue,
      getStagnantLevelType,
      getStagnantLevelLabel,
      getStagnantDaysClass,
      getTimelineItemType,
      handleSelectionChange,
      handleCurrentChange,
      handleSizeChange
    }
  }
}
</script>

<style>
.stagnant-warning-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.stagnant-card {
  margin-bottom: 20px;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
  height: 100px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-trend {
  font-size: 12px;
  color: #909399;
}

.trend-up {
  color: #F56C6C;
}

.trend-down {
  color: #67C23A;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.days-light {
  color: #909399;
}

.days-medium {
  color: #E6A23C;
  font-weight: bold;
}

.days-severe {
  color: #F56C6C;
  font-weight: bold;
}

.days-zombie {
  color: #F56C6C;
  font-weight: bold;
  text-decoration: underline;
}

.batch-summary {
  text-align: center;
  margin-bottom: 15px;
}

.single-material {
  margin-bottom: 15px;
}

.history-container {
  padding: 10px;
}

.history-quantity {
  margin-top: 5px;
  font-weight: bold;
}

/* 确保下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}
</style> 